<?php

if (!function_exists("xml_to_array")) {
    function xml_to_array($xml)
    {
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if (preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; $i++) {
                $subxml = $matches[2][$i];
                $key = $matches[1][$i];
                if (preg_match($reg, $subxml)) {
                    $arr[$key] = xml_to_array($subxml);
                } else {
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }
}







if (!function_exists("strexists")) {
    /**
     * 判断字符串是否包含子串
     * @param string $string 在该字符串中进行查找
     * @param string $find 需要查找的字符串
     * @return boolean
     */
    function strexists($string, $find)
    {
        return !(strpos($string, $find) === false);
    }
}

if (!function_exists('is_array2')) {
    function is_array2($array)
    {
        if (is_array($array)) {
            foreach ($array as $k => $v) {
                return is_array($v);
            }
            return false;
        }
        return false;
    }
}


if (!function_exists("array_column")) {

    function array_column($input = null, $columnKey = null, $indexKey = null)
    {
        // Using func_get_args() in order to check for proper number of
        // parameters and trigger errors exactly as the built-in array_column()
        // does in PHP 5.5.
        $argc = func_num_args();
        $params = func_get_args();
        if ($argc < 2) {
            trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
            return null;
        }
        if (!is_array($params[0])) {
            trigger_error(
                'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
                E_USER_WARNING
            );
            return null;
        }
        if (!is_int($params[1])
            && !is_float($params[1])
            && !is_string($params[1])
            && $params[1] !== null
            && !(is_object($params[1]) && method_exists($params[1], '__toString'))
        ) {
            trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
            return false;
        }
        if (isset($params[2])
            && !is_int($params[2])
            && !is_float($params[2])
            && !is_string($params[2])
            && !(is_object($params[2]) && method_exists($params[2], '__toString'))
        ) {
            trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
            return false;
        }
        $paramsInput = $params[0];
        $paramsColumnKey = ($params[1] !== null) ? (string)$params[1] : null;
        $paramsIndexKey = null;
        if (isset($params[2])) {
            if (is_float($params[2]) || is_int($params[2])) {
                $paramsIndexKey = (int)$params[2];
            } else {
                $paramsIndexKey = (string)$params[2];
            }
        }
        $resultArray = array();
        foreach ($paramsInput as $row) {
            $key = $value = null;
            $keySet = $valueSet = false;
            if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
                $keySet = true;
                $key = (string)$row[$paramsIndexKey];
            }
            if ($paramsColumnKey === null) {
                $valueSet = true;
                $value = $row;
            } elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
                $valueSet = true;
                $value = $row[$paramsColumnKey];
            }
            if ($valueSet) {
                if ($keySet) {
                    $resultArray[$key] = $value;
                } else {
                    $resultArray[] = $value;
                }
            }
        }
        return $resultArray;
    }
}

if (!function_exists('objectArray')) {
    function objectArray($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = objectArray($value);
            }
        }
        return $array;
    }
}






if (!function_exists('weAccount')) {
    /**
     * 获取微擎账号体系
     * @return NULL|WeAccount
     */
    function weAccount()
    {
       /* load()->model('account');
        return WeAccount::create();*/
    }
}





if (!function_exists('array_child_kv_exists')) {
    function array_child_kv_exists($array, $childKey, $value)
    {
        $result = false;

        if (is_array($array)) {
            foreach ($array as $v) {
                if (is_array($v) && isset($v[$childKey])) {
                    $result += $v[$childKey] == $value;
                }
            }
        }

        return $result;
    }
}

if (!function_exists('widget')) {
    function widget($class, $params = [])
    {
        return (new $class($params))->run();
    }
}



if (!function_exists('plugin')) {

    function plugin($id)
    {
        return app('plugins')->getPlugin($id);
    }
}

if (!function_exists('plugin_assets')) {

    function plugin_assets($id, $relativeUri)
    {
        if ($plugin = plugin($id)) {
            return $plugin->assets($relativeUri);
        } else {
            throw new InvalidArgumentException("No such plugin.");
        }
    }
}


if (!function_exists('float_greater')) {
    function float_greater($number, $other_number)
    {
        return bccomp($number, $other_number) === 1;
    }
}
if (!function_exists('float_lesser')) {
    function float_lesser($number, $other_number)
    {
        return bccomp($number, $other_number) === -1;
    }
}
if (!function_exists('float_equal')) {
    function float_equal($number, $other_number)
    {
        return bccomp($number, $other_number) === 0;
    }

}

if (!function_exists('sdd')) {
    function sdd()
    {
        global $testDd;
        $testDd = !$testDd;
    }
}
if (!function_exists('tdd')) {
    function tdd()
    {
        global $testDd;
        if ($testDd) {
            dd(func_get_args());
        }
    }

}


if (!function_exists('yz_array_set')) {
    function yz_array_set($array, $key, $value)
    {
        $keys = explode('.', $key);
        while (count($keys) > 1) {
            $key = array_shift($keys);

            // If the key doesn't exist at this depth, we will just create an empty array
            // to hold the next value, allowing us to create the arrays to hold final
            // values at the correct depth. Then we'll keep digging into the array.
            if (!isset($array[$key]) || !is_array($array[$key])) {
                $array[$key] = [];
            }
            $array = &$array[$key];
        }
        $array[array_shift($keys)] = $value;

        return $array;
    }
}
if (!function_exists('trace_log')) {
    /**
     * @return \Illuminate\Foundation\Application|mixed
     */
    function trace_log(){
        return app('Log.trace');
    }
}

if (!function_exists('debug_log')) {
    /**
     * @return \Illuminate\Foundation\Application|mixed
     */
    function debug_log(){
        return app('Log.debug');
    }
}

if (!function_exists('randNum')) {
    /**
     * 获取随机字符串
     * @param number $length 字符串长度
     * @param boolean $numeric 是否为纯数字
     * @return string
     */
     function randNum($length, $numeric = FALSE) {
        $length = intval($length);
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }
}

if (!function_exists('file_random_name')) {
    function file_random_name($dir, $ext)
    {
        do {
            $filename = random(30) . '.' . $ext;
        } while (file_exists($dir . $filename));

        return $filename;
    }
}

if (!function_exists('random')) {
    function random($length, $numeric = FALSE)
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }
}

if (!function_exists('is_error')) {
    function is_error($data)
    {
        if (empty($data) || !is_array($data) || !array_key_exists('errno', $data) || (array_key_exists('errno', $data) && $data['errno'] == 0)) {
            return false;
        } else {
            return true;
        }
    }
}






if (!function_exists('array_elements')) {
    function array_elements($keys, $src, $default = FALSE)
    {
        $return = array();
        if (!is_array($keys)) {
            $keys = array($keys);
        }
        foreach ($keys as $key) {
            if (isset($src[$key])) {
                $return[$key] = $src[$key];
            } else {
                $return[$key] = $default;
            }
        }
        return $return;
    }
}

if (!function_exists('sizecount')) {
    function sizecount($size)
    {
        if ($size >= 1073741824) {
            $size = round($size / 1073741824 * 100) / 100 . ' GB';
        } elseif ($size >= 1048576) {
            $size = round($size / 1048576 * 100) / 100 . ' MB';
        } elseif ($size >= 1024) {
            $size = round($size / 1024 * 100) / 100 . ' KB';
        } else {
            $size = $size . ' Bytes';
        }
        return $size;
    }
}



if (!function_exists('file_is_image')) {
    function file_is_image($url)
    {
        if (!parse_path($url)) {
            return false;
        }
        $pathinfo = pathinfo($url);
        $extension = strtolower($pathinfo['extension']);

        return !empty($extension) && in_array($extension, array('jpg', 'jpeg', 'gif', 'png'));
    }
}




if (!function_exists('pagination')) {
    function pagination($total, $pageIndex, $pageSize = 15, $url = '', $context = array('before' => 5, 'after' => 4, 'ajaxcallback' => '', 'callbackfuncname' => ''))
    {
        $pdata = array(
            'tcount' => 0,
            'tpage' => 0,
            'cindex' => 0,
            'findex' => 0,
            'pindex' => 0,
            'nindex' => 0,
            'lindex' => 0,
            'options' => ''
        );
        if (!$context['before']) {
            $context['before'] = 5;
        }
        if (!$context['after']) {
            $context['after'] = 4;
        }

        if ($context['ajaxcallback']) {
            $context['isajax'] = true;
        }

        if ($context['callbackfuncname']) {
            $callbackfunc = $context['callbackfuncname'];
        }

        $pdata['tcount'] = $total;
        $pdata['tpage'] = (!$pageSize || $pageSize < 0) ? 1 : intval(ceil($total / $pageSize));
        if ($pdata['tpage'] <= 1) {
            return '';
        }
        $cindex = $pageIndex;
        $cindex = min($cindex, $pdata['tpage']);
        $cindex = max($cindex, 1);
        $pdata['cindex'] = $cindex;
        $pdata['findex'] = 1;
        $pdata['pindex'] = $cindex > 1 ? $cindex - 1 : 1;
        $pdata['nindex'] = $cindex < $pdata['tpage'] ? $cindex + 1 : $pdata['tpage'];
        $pdata['lindex'] = $pdata['tpage'];

        if ($context['isajax']) {
            if (!$url) {
                $url = '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET);
            }
            $pdata['faa'] = 'href="javascript:;" page="' . $pdata['findex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['findex'] . '\', this);"' : '');
            $pdata['paa'] = 'href="javascript:;" page="' . $pdata['pindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['pindex'] . '\', this);"' : '');
            $pdata['naa'] = 'href="javascript:;" page="' . $pdata['nindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['nindex'] . '\', this);"' : '');
            $pdata['laa'] = 'href="javascript:;" page="' . $pdata['lindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['lindex'] . '\', this);"' : '');
        } else {
            if ($url) {
                $pdata['faa'] = 'href="?' . str_replace('*', $pdata['findex'], $url) . '"';
                $pdata['paa'] = 'href="?' . str_replace('*', $pdata['pindex'], $url) . '"';
                $pdata['naa'] = 'href="?' . str_replace('*', $pdata['nindex'], $url) . '"';
                $pdata['laa'] = 'href="?' . str_replace('*', $pdata['lindex'], $url) . '"';
            } else {
                $_GET['page'] = $pdata['findex'];
                $pdata['faa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
                $_GET['page'] = $pdata['pindex'];
                $pdata['paa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
                $_GET['page'] = $pdata['nindex'];
                $pdata['naa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
                $_GET['page'] = $pdata['lindex'];
                $pdata['laa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
            }
        }

        $html = '<div><ul class="pagination pagination-centered">';
        $html .= "<li><a {$pdata['faa']} class=\"pager-nav\">首页</a></li>";
        empty($callbackfunc) && $html .= "<li><a {$pdata['paa']} class=\"pager-nav\">&laquo;上一页</a></li>";

        if (!$context['before'] && $context['before'] != 0) {
            $context['before'] = 5;
        }
        if (!$context['after'] && $context['after'] != 0) {
            $context['after'] = 4;
        }

        if ($context['after'] != 0 && $context['before'] != 0) {
            $range = array();
            $range['start'] = max(1, $pdata['cindex'] - $context['before']);
            $range['end'] = min($pdata['tpage'], $pdata['cindex'] + $context['after']);
            if ($range['end'] - $range['start'] < $context['before'] + $context['after']) {
                $range['end'] = min($pdata['tpage'], $range['start'] + $context['before'] + $context['after']);
                $range['start'] = max(1, $range['end'] - $context['before'] - $context['after']);
            }
            for ($i = $range['start']; $i <= $range['end']; $i++) {
                if ($context['isajax']) {
                    $aa = 'href="javascript:;" page="' . $i . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $i . '\', this);"' : '');
                } else {
                    if ($url) {
                        $aa = 'href="?' . str_replace('*', $i, $url) . '"';
                    } else {
                        $_GET['page'] = $i;
                        $aa = 'href="?' . http_build_query($_GET) . '"';
                    }
                }
                if (!empty($context['isajax'])) {
                    $html .= ($i == $pdata['cindex'] ? '<li class="active">' : '<li>') . "<a {$aa}>" . $i . '</a></li>';
                } else {
                    $html .= ($i == $pdata['cindex'] ? '<li class="active"><a href="javascript:;">' . $i . '</a></li>' : "<li><a {$aa}>" . $i . '</a></li>');
                }
            }
        }

        if ($pdata['cindex'] < $pdata['tpage']) {
            empty($callbackfunc) && $html .= "<li><a {$pdata['naa']} class=\"pager-nav\">下一页&raquo;</a></li>";
            $html .= "<li><a {$pdata['laa']} class=\"pager-nav\">尾页</a></li>";
        }
        $html .= '</ul></div>';
        return $html;
    }
}

if (!function_exists('http_build_query')) {
    /**
     * 为了兼容微擎使用此方法
     * @param $formdata
     * @param null $numeric_prefix
     * @param null $arg_separator
     * @return bool|string
     */
    function http_build_query($formdata, $numeric_prefix = null, $arg_separator = null)
    {
        if (!is_array($formdata))
            return false;
        if ($arg_separator == null)
            $arg_separator = '&';
        return http_build_recursive($formdata, $arg_separator);
    }
}





if (!function_exists('error')) {
    /**
     * 为了兼容微擎使用此方法
     * @param $errno
     * @param string $message
     * @return array
     */
    function error($errno, $message = '')
    {
        return array(
            'errno' => $errno,
            'message' => $message,
        );
    }
}

if (!function_exists('http_build_recursive')) {
    /**
     * 为了兼容微擎使用此方法
     * @param $formdata
     * @param $separator
     * @param string $key
     * @param string $prefix
     * @return string
     */
    function http_build_recursive($formdata, $separator, $key = '', $prefix = '')
    {
        $rlt = '';
        foreach ($formdata as $k => $v) {
            if (is_array($v)) {
                if ($key)
                    $rlt .= http_build_recursive($v, $separator, $key . '[' . $k . ']', $prefix);
                else
                    $rlt .= http_build_recursive($v, $separator, $k, $prefix);
            } else {
                if ($key)
                    $rlt .= $prefix . $key . '[' . urlencode($k) . ']=' . urldecode($v) . '&';
                else
                    $rlt .= $prefix . urldecode($k) . '=' . urldecode($v) . '&';
            }
        }
        return $rlt;
    }
}

if (!function_exists('ihttp_response_parse')) {
    /**
     * 为了兼容微擎使用此方法
     * @param $data
     * @param bool $chunked
     * @return array
     */
    function ihttp_response_parse($data, $chunked = false)
    {
        $rlt = array();

        $headermeta = explode('HTTP/', $data);
        if (count($headermeta) > 2) {
            $data = 'HTTP/' . array_pop($headermeta);
        }
        $pos = strpos($data, "\r\n\r\n");
        $split1[0] = substr($data, 0, $pos);
        $split1[1] = substr($data, $pos + 4, strlen($data));

        $split2 = explode("\r\n", $split1[0], 2);
        preg_match('/^(\S+) (\S+) (.*)$/', $split2[0], $matches);
        $rlt['code'] = $matches[2] ?  : 200;
        $rlt['status'] = $matches[3] ?  : 'OK';
        $rlt['responseline'] = $split2[0] ? : '';
        $header = explode("\r\n", $split2[1]);
        $isgzip = false;
        $ischunk = false;
        foreach ($header as $v) {
            $pos = strpos($v, ':');
            $key = substr($v, 0, $pos);
            $value = trim(substr($v, $pos + 1));
            if (is_array($rlt['headers'][$key])) {
                $rlt['headers'][$key][] = $value;
            } elseif ($rlt['headers'][$key]) {
                $temp = $rlt['headers'][$key];
                unset($rlt['headers'][$key]);
                $rlt['headers'][$key][] = $temp;
                $rlt['headers'][$key][] = $value;
            } else {
                $rlt['headers'][$key] = $value;
            }
            if (!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
                $isgzip = true;
            }
            if (!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
                $ischunk = true;
            }
        }
        if ($chunked && $ischunk) {
            $rlt['content'] = ihttp_response_parse_unchunk($split1[1]);
        } else {
            $rlt['content'] = $split1[1];
        }
        if ($isgzip && function_exists('gzdecode')) {
            $rlt['content'] = gzdecode($rlt['content']);
        }

        $rlt['meta'] = $data;
        if ($rlt['code'] == '100') {
            return ihttp_response_parse($rlt['content']);
        }
        return $rlt;
    }
}

if (!function_exists('ihttp_response_parse_unchunk')) {
    /**
     * 为了兼容微擎使用此方法
     * @param null $str
     * @return bool|string|null
     */
    function ihttp_response_parse_unchunk($str = null)
    {
        if (!is_string($str) or strlen($str) < 1) {
            return false;
        }
        $eol = "\r\n";
        $add = strlen($eol);
        $tmp = $str;
        $str = '';
        do {
            $tmp = ltrim($tmp);
            $pos = strpos($tmp, $eol);
            if ($pos === false) {
                return false;
            }
            $len = hexdec(substr($tmp, 0, $pos));
            if (!is_numeric($len) or $len < 0) {
                return false;
            }
            $str .= substr($tmp, ($pos + $add), $len);
            $tmp = substr($tmp, ($len + $pos + $add));
            $check = trim($tmp);
        } while ($check);
        unset($tmp);
        return $str;
    }
}


if (!function_exists('ihttp_socketopen')) {
    function ihttp_socketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15)
    {
        $fp = '';
        if (function_exists('fsockopen')) {
            $fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
        } elseif (function_exists('pfsockopen')) {
            $fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
        } elseif (function_exists('stream_socket_client')) {
            $fp = @stream_socket_client($hostname . ':' . $port, $errno, $errstr, $timeout);
        }
        return $fp;
    }
}




if (!function_exists('file_tree')) {
    function file_tree($path, $include = array()) {
        $files = array();
        if ($include) {
            $ds = glob($path . '/{' . implode(',', $include) . '}', GLOB_BRACE);
        } else {
            $ds = glob($path . '/*');
        }
        if (is_array($ds)) {
            foreach ($ds as $entry) {
                if (is_file($entry)) {
                    $files[] = $entry;
                }
                if (is_dir($entry)) {
                    $rs = file_tree($entry);
                    foreach ($rs as $f) {
                        $files[] = $f;
                    }
                }
            }
        }

        return $files;
    }
}

if (!function_exists('parse_path')) {
    function parse_path($path)
    {
        $danger_char = array('../', '{php', '<?php', '<%', '<?', '..\\', '\\\\', '\\', '..\\\\', '%00', '\0', '\r');
        foreach ($danger_char as $char) {
            if (strexists($path, $char)) {
                return false;
            }
        }
        return $path;
    }
}

if (!function_exists('bytecount')) {
    function bytecount($str)
    {
        if (strtolower($str[strlen($str) - 1]) == 'b') {
            $str = substr($str, 0, -1);
        }
        if (strtolower($str[strlen($str) - 1]) == 'k') {
            return floatval($str) * 1024;
        }
        if (strtolower($str[strlen($str) - 1]) == 'm') {
            return floatval($str) * 1048576;
        }
        if (strtolower($str[strlen($str) - 1]) == 'g') {
            return floatval($str) * 1073741824;
        }
    }
}

if (!function_exists('attachment_alioss_datacenters')) {
    function attachment_alioss_datacenters()
    {
        $bucket_datacenter = array(
            'oss-cn-hangzhou' => '杭州数据中心',
            'oss-cn-qingdao' => '青岛数据中心',
            'oss-cn-beijing' => '北京数据中心',
            'oss-cn-hongkong' => '香港数据中心',
            'oss-cn-shenzhen' => '深圳数据中心',
            'oss-cn-shanghai' => '上海数据中心',
            'oss-us-west-1' => '美国硅谷数据中心',
        );

        return $bucket_datacenter;
    }
}


if (!function_exists('getimagesizefromstring')) {
    function getimagesizefromstring($string_data) {
        $uri = 'data://application/octet-stream;base64,'  . base64_encode($string_data);
        return getimagesize($uri);
    }
}

if (!function_exists('yz_buildCustomPostFields')) {

    /**
     * Build custom post fields for safe multipart POST request for php before 5.5.
     * @param $fields array of key -> value fields to post.
     * @return $boundary and encoded post fields.
     */
    function yz_buildCustomPostFields($fields)
    {
        // invalid characters for "name" and "filename"
        static $disallow = array("\0", "\"", "\r", "\n");

        // initialize body
        $body = array();

        // build normal parameters
        foreach ($fields as $key => $value) {
            $key = str_replace($disallow, "_", $key);
            $body[] = implode("\r\n", array(
                "Content-Disposition: form-data; name=\"{$key}\"",
                '',
                filter_var($value),
            ));
        }

        // generate safe boundary
        do {
            $boundary = "---------------------" . md5(mt_rand() . microtime());
        } while (preg_grep("/{$boundary}/", $body));

        // add boundary for each parameters
        foreach ($body as &$part) {
            $part = "--{$boundary}\r\n{$part}";
        }
        unset($part);

        // add final boundary
        $body[] = "--{$boundary}--";
        $body[] = '';

        return array($boundary, implode("\r\n", $body));
    }
}

if (!function_exists('resource_get')) {
    function resource_get($file, $depth=2)
    {
        if (config('app.framework') == 'platform') {
            return '/' . $file;
        }

        $path = $depth == 2 ? '../..' : '..';

        return $path . '/addons/yun_shop/' . $file;
    }
}


if (!function_exists('tpl_form_field_color')) {
    function tpl_form_field_color($name, $value = '')
    {
        $s = '';
        if (!defined('TPL_INIT_COLOR')) {
            $s = '
		<script type="text/javascript">
			$(function(){
				$(".colorpicker").each(function(){
					var elm = this;
					util.colorpicker(elm, function(color){
						$(elm).parent().prev().prev().val(color.toHexString());
						$(elm).parent().prev().css("background-color", color.toHexString());
					});
				});
				$(".colorclean").click(function(){
					$(this).parent().prev().prev().val("");
					$(this).parent().prev().css("background-color", "#FFF");
				});
			});
		</script>';
            define('TPL_INIT_COLOR', true);
        }
        $s .= '
		<div class="row row-fix">
			<div class="col-xs-8 col-sm-8" style="padding-right:0;">
				<div class="input-group">
					<input class="form-control" type="text" name="'.$name.'" placeholder="请选择颜色" value="'.$value.'">
					<span class="input-group-addon" style="width:35px;border-left:none;background-color:'.$value.'"></span>
					<span class="input-group-btn">
						<button class="btn btn-default colorpicker" type="button">选择颜色 <i class="fa fa-caret-down"></i></button>
						<button class="btn btn-default colorclean" type="button"><span><i class="fa fa-remove"></i></span></button>
					</span>
				</div>
			</div>
		</div>
		';
        return $s;
    }
}



if (!function_exists('safe_gpc_int')) {
    function safe_gpc_int($value, $default = 0)
    {
        if (strpos($value, '.') !== false) {
            $value = floatval($value);
            $default = floatval($default);
        } else {
            $value = intval($value);
            $default = intval($default);
        }

        if (!$value && $default != $value) {
            $value = $default;
        }
        return $value;
    }
}




if (!function_exists('iunserializer')) {
    function iunserializer($value)
    {
        if (!$value) {
            return array();
        }
        if (!is_serialized($value)) {
            return $value;
        }
        $result = unserialize($value);
        if ($result === false) {
            $temp = preg_replace_callback('!s:(\d+):"(.*?)";!s', function ($matchs) {
                return 's:' . strlen($matchs[2]) . ':"' . $matchs[2] . '";';
            }, $value);
            return unserialize($temp);
        } else {
            return $result;
        }
    }
}

if (!function_exists('is_serialized')) {
    function is_serialized($data, $strict = true)
    {
        if (!is_string($data)) {
            return false;
        }
        $data = trim($data);
        if ('N;' == $data) {
            return true;
        }
        if (strlen($data) < 4) {
            return false;
        }
        if (':' !== $data[1]) {
            return false;
        }
        if ($strict) {
            $lastc = substr($data, -1);
            if (';' !== $lastc && '}' !== $lastc) {
                return false;
            }
        } else {
            $semicolon = strpos($data, ';');
            $brace = strpos($data, '}');
            if (false === $semicolon && false === $brace)
                return false;
            if (false !== $semicolon && $semicolon < 3)
                return false;
            if (false !== $brace && $brace < 4)
                return false;
        }
        $token = $data[0];
        switch ($token) {
            case 's' :
                if ($strict) {
                    if ('"' !== substr($data, -2, 1)) {
                        return false;
                    }
                } elseif (false === strpos($data, '"')) {
                    return false;
                }
            case 'a' :
                return (bool)preg_match("/^{$token}:[0-9]+:/s", $data);
            case 'O' :
                return false;
            case 'b' :
            case 'i' :
            case 'd' :
                $end = $strict ? '$' : '';
                return (bool)preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
        }
        return false;
    }
}










if (!function_exists('resource_absolute')) {
    function resource_absolute($file)
    {
        if (config('app.framework') == 'platform') {
            return '/' . $file;
        }

        return  '/addons/yun_shop/' . $file;
    }
}


if (!function_exists('change_to_local_url')) {
    function change_to_local_url($file)
    {
        if (strexists($file, 'storage')) {
            $file = strstr($file, 'storage');
            return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
        }
        if (strexists($file, 'static/upload/')) {
            $file = strstr($file, 'static/upload/');
            // 将 static/upload/ 路径转换为 storage/ 路径
            $file = str_replace('static/upload/', 'storage/', $file);
            return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
        }
        if (strexists($file, 'attachment/')) {
            $file = strstr($file, 'attachment/');
            return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
        }
        $disks = config('filesystems.disks');
        foreach ($disks as $key => $disk) {
            if (strexists($file, $key)) {
                $file = strstr($file, $key);
                break;
            }
        }
        if (config('app.framework') == 'platform') {
            $file = request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . 'storage/' . $file;
        } else {
            $file = request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . 'attachment/' . $file;
        }
        return $file;
    }
}

if (!function_exists('setSystemVersion')) {
    function setSystemVersion($version, $file)
    {
        $str = file_get_contents(base_path('config/') . $file);
        $str = preg_replace('/"[\d\.]+"/', '"'. $version . '"', $str);

        file_put_contents(base_path('config/') . $file, $str);
    }
}


if (!function_exists('substrCut')) {
	/**
	 * 只保留字符串首尾字符，隐藏中间用*代替（两个字符时只显示第一个）
	 * @param string $user_name 姓名
	 * @return string 格式化后的姓名
	 */
	function substrCut($user_name) {
		$strlen = mb_strlen($user_name, 'utf-8');
		$firstStr = mb_substr($user_name, 0, 1, 'utf-8');
		$lastStr = mb_substr($user_name, -1, 1, 'utf-8');
		if ($strlen < 2) {
			return $user_name;
		} else {
			return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
		}
	}
}

if (!function_exists('validatePassword')) {
    /**
     * 密码强度效验统一规则（更多用于平台的密码强度效验）
     * @param $password
     * @return string
     */
    function validatePassword($password) {
        if (!preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[.!~@#$%^&*?\(\)+_-]).{8,18}$/', $password)) {
            return '密码长度至少为8位,要求包括数字，大小写字母和特殊字符';
        }
        return true;
    }

}



